<?php

namespace app\home\controller;

use think\captcha\Captcha;

use think\Controller;

use think\Db;

use think\Request;

class Index extends Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->UserModel = model('User.User');

        // 获取用户的所有信息
        $UserList = model('User.User')->column('id,salt');

        // 获取cookie的数据
        $LoginUser = cookie('LoginUser') ? cookie('LoginUser') : '';

        $this->RecordModel = model("User.Record");
        $this->PostModel = model("Post.Post");

        $userid = 0;
        foreach ($UserList as $key => $value) {
            $usersalt = md5($key . $value);
            if ($LoginUser == $usersalt) {
                $userid = $key;
                break;
            }
        }
        // 通过userid获取用户信息
        // $UserInfo = Db::table('pre_user')->find($userid);
        $UserInfo = model('User.User')->find($userid);

        $sing = $this->RecordModel->whereTime('createtime', 'today')->where(['userid' => $UserInfo['id'], 'state' => 4])->find();

        //  用户消费记录
        if ($sing) {
            $UserInfo['sing'] = 1;
        }

        $UserInfo = $UserInfo ? $UserInfo : [];

        // 把用户数据给继承home公共控制器的子控制器
        $this->LoginUser = $UserInfo;
        // 如果找到了该用户，则将数据赋值至视图
        $this->assign([
            'LoginUser' => $UserInfo
        ]);
    }

    public function index()
    {
        // 获取分类id
        $cateid = $this->request->param('cateid', '');

        // 帖子状态
        $state = $this->request->param('state', '');

        // 采纳
        $accept = $this->request->param('accept', 0);

        // 关键字
        $keyword = $this->request->param('keyword', '');

        // 条件数组
        $where = [];
        if (!empty($cateid)) {
            // ['字段', '表达式', '值']
            $where['cateid'] = $cateid;
        }

        if (!empty($state)) {
            $where['state'] = $state;
        }

        if ($accept == 0) {
            // where `accept` is null
            $where['accept'] = ['exp', Db::raw('is null')];
        } elseif ($accept == 1) {
            $where['accept'] = ['exp', Db::raw('is not null')];
        }

        if (!empty($keyword)) {
            $where['title'] = ['like', "%$keyword%"];
        }

        // 帖子分类
        $CateList = model('Post.Cate')->order('weigh', 'desc')->limit(7)->select();

        // 查询签到积分
        $SignPoint = model('config')->where('key', 'SignPoint')->value('value');

        // 获取帖子  分页
        $PostList = model('Post.Post')->with('user', 'cate')->where($where)
            ->order('post.createtime', 'desc')->paginate(1, false, ['query' => Request::instance()->param()]);

        // 本周热议帖子  按评论数最多排行
        $HotPost = model('Post.Comment')->with(['post'])->field("COUNT(*) as num, post.title, post.id")
            ->whereTime('comment.createtime', 'week')->order('num desc')->group('comment.postid')->limit(5)->select();

        // 回帖周榜
        $ReplyBoard = model('Post.Comment')->with(['post', 'user'])->field("COUNT('userid') as num, user.nickname, user.id, user.avatar")
             ->whereTime('comment.createtime', 'week')->order('num desc')->group('comment.postid')->limit(4)->select();
        // halt($ReplyBoard);
        return $this->view->fetch('', [
            'CateList' => $CateList,
            'cateid' => $cateid,
            'PostList' => $PostList,
            'SignPoint' => $SignPoint,
            'state' => $state,
            'accept' => $accept,
            'HotPost' => $HotPost,
            'ReplyBoard' => $ReplyBoard
        ]);
    }

    // 帖子详情
    public function info()
    {
        if ($this->request->isPost()) {
            // 点赞
            $action = $this->request->param('action');
            if ($action == 'aaa') {
                $id = $this->request->param('id');
                $u = model('Post.Comment')->find($id);
                if ($u == null) {
                    $this->error('无法点赞该评论', null, null, 2);
                }

                $data = [
                    'id' => $id,
                    'userid' => $this->LoginUser['id'],
                    'postid' => $u['postid'],
                ];
                // 字符串转数组 “，”分割
                $likearr = explode(",", $u['like']);
                if (!in_array( $this->LoginUser['id'], $likearr)) {
                    array_push($likearr, $this->LoginUser['id']);
                    // 数组转字符串
                    $likeStr = implode(',', $likearr);
                    $likeStr = ltrim($likeStr, ',');
                    $data['like'] = $likeStr;
                    $res = model('Post.Comment')->isUpdate(true)->save($data);
                    if ($res) {
                        $this->success('点赞成功', null, null, 2);
                        return ;
                    } else {
                        $this->error('点赞失败', null, null, 2);
                        return ;
                    }
                } else {
                    foreach($likearr as $k=>$v){
                        if($v == $this->LoginUser['id']){
                            unset($likearr[$k]);
                        }
                    }
                    // 数组转字符串
                    $likeStr = implode(',', $likearr);
                    $likeStr = ltrim($likeStr, ',');
                    $data['like'] = $likeStr;
                    // halt($data);
                    $res = model('Post.Comment')->isUpdate(true)->save($data);
                    if ($res) {
                        $this->success('已取消点赞', null, null, 2);
                        return ;
                    } else {
                        $this->error('点赞失败', null, null, 2);
                        return ;
                    }
                }
                
            }
            
            // 删除评论
            if ($action == 'delCom') {
                // halt($action);
                $id = $this->request->param('id');
                $info = model('Post.Comment')->find($id);
                // halt($info);
                if (!$info) {
                    $this->error('无法删除该评论');
                }
                // $this->success('可以删除该评论');
                $res = DelComent($id);
                if ($res == 1) {
                    $this->success('删除成功');
                    return ;
                } else {
                    $this->error('删除失败');
                    return ;
                }
            }
        }

        // 获取参数
        $postid = $this->request->param('postid', 0);
        // halt($postid);
        // 根据参数postid获取帖子信息 
        $PostInfo = model("Post.Post")->with(['cate', 'user'])->where('post.id', $postid)->find();
        if (empty($PostInfo)) {
            $this->error('帖子不存在');
        }

        $userid = !empty($this->LoginUser['id']) ? $this->LoginUser['id'] : 0;
        $User = $this->UserModel->find($userid);

        // if (!$User) {
        //     $this->error('请先登录', url('home/index/index'), null, 1);
        // }

        // 按照id 进行更新浏览量
        // 字符串转数组
        $VisitArr = explode(',', $PostInfo['visit']);
        if (!in_array($User['id'], $VisitArr)) {
            $VisitArr[] = $User['id'];
            $VisitStr = implode(',', $VisitArr);
            $VisitStr = ltrim($VisitStr, ',');
            $this->PostModel->where('id', $postid)->update(['visit' => $VisitStr]);
        }
        $VisitCount = !empty($VisitArr) ? count($VisitArr) : 1;

        // 判断该帖子是否被当前用户收藏
        $collect = model('User.Collect')->where(['userid' => $userid, 'postid' => $postid])->find();

        // 查询评论数据
        $CommentList = model("Post.Comment")->with('user')->where('postid', $postid)->order('comment.createtime')->select();
        $CommentList = CommentTree($CommentList, 0, $User);

        return $this->fetch('', [
            'userid' => $userid,
            'PostInfo' => $PostInfo,
            'VisitCount' => $VisitCount,
            'collect' => $collect,
            'CommentList' => $CommentList
        ]);
    }

    // 签到
    public function sign()
    {
        if ($this->request->isAjax()) {
            if (empty($this->LoginUser)) {
                $this->error('请先登录');
            }
            // 查询今天是否签到
            $sing = $this->RecordModel->whereTime('createtime', 'today')->where(['userid' => $this->LoginUser['id'], 'state' => 4])->find();
            if ($sing) {
                $this->error('您已签到了');
            }
            /**
             * 消费记录表 新增一条记录
             */
            // 开启事务
            $this->UserModel->startTrans();
            $this->RecordModel->startTrans();

            // 获取到签到的积分
            $signPoint = model('config')->where(['key' => 'SignPoint'])->value('value');

            // 用户的积分加上签到的积分
            $Point = bcadd($this->LoginUser['point'], $signPoint);
            // 更新数据
            $UserData = [
                'id' => $this->LoginUser['id'],
                'point' => $Point
            ];
            $UserStatus = $this->UserModel->isUpdate(true)->save($UserData);
            if ($UserStatus == false) {
                $this->error('签到失败');
            }
            // 消费记录
            $RecordData = [
                'userid' => $this->LoginUser['id'],
                'point' => $signPoint,
                'content' => "您在" . date('Y-m-d H:i', time()) . "通过【签到】获取了{$signPoint}积分",
                'state' => 4
            ];

            $RecordStatus = $this->RecordModel->validate('common/User/Record')->save($RecordData);
            if ($RecordStatus == false) {
                $this->UserModel->rollback();
                $this->error($this->RecordModel->getError());
            }
            if ($UserStatus == false || $RecordStatus == false) {
                $this->UserModel->rollback();
                $this->RecordModel->rollback();
                $this->error('签到失败', null, null, 1);
            } else {
                $this->UserModel->commit();
                $this->RecordModel->commit();
                $this->success('签到成功', null, null, 1);
            }
        }
    }

    // 注册
    public function register()
    {
        // 判断是否为post请求，参数为空时获取所有参数。
        if ($this->request->isPost()) {
            // param函数 可以自动判断是post还是get请求
            $params = $this->request->param();
            // 打印函数halt
            // halt($params);

            // 判断验证码是否正确
            if (!Captcha_check($params['vercode'])) {
                // 跳转到中间页  参数：提示信息  跳转地址  数据  时间 请求头
                $this->error('验证码错误');
            }

            // 判断密码是否一致
            if ($params['pass'] != $params['repass']) {
                $this->error("密码不一致");
            }

            // 生成密码盐
            $salt = build_ranstr();

            // 密码加密
            $password = md5($params['pass'] . $salt);

            // Db类或模型 -> 增删改查
            $point = Db::name('config')->where('key', 'RegisterPoint')->value('value');
            // halt($point);
            //封装插入数据库的数组
            $data = [
                'email' => $params['email'],
                'nickname' => $params['nickname'],
                'password' => $password,
                'salt' => $salt,
                'sex' => 0,
                'auth' => 0,
                'vip' => 1,
                'point' => $point
            ];
            $res = $this->UserModel->validate('common/User/User')->save($data);
            if ($res === false) {
                $this->error($this->UserModel->getError());
            } else {
                $this->success('注册成功', url('home/index/login'));
            }
        }
        // 输出视图
        return $this->fetch();
    }

    // 登录
    public function login()
    {
        if ($this->request->isPost()) {
            $params = $this->request->param();

            // 判断验证码是否正确
            if (!captcha_check($params['vercode'])) {
                $this->error('验证码错误');
            }

            // 通过邮箱查询是否存在该用户
            $User = $this->UserModel->where(['email' => $params['email']])->find();
            if (!$User) {
                $this->error("该用户不存在");
            }
            $password = md5($params['pass'] . $User['salt']);

            if ($password != $User['password']) {
                $this->error('密码错误');
            }
            $data = md5($User['id'] . $User['salt']);
            cookie('LoginUser', $data);
            $this->success('登录成功', url('home/user/index'));
        }
        return $this->fetch();
    }

    // 退出登录 
    public function logout()
    {
        cookie('LoginUser', null);
        $this->success('退出成功', url('home/index/index'));
    }

    // 邮箱认证
    public function auth()
    {
        $email = $this->request->param('email');
        $UserList = $this->UserModel->column('email, salt');
        $UserEmail = '';
        // halt($UserList);
        foreach ($UserList as $key => $value) {
            $es = md5($key . $value);
            if ($es == $email) {
                $UserEmail = $key;
                break;
            }
        }
        $user = $this->UserModel->where('email', $UserEmail)->find();
        // halt($user);
        if (!$user) {
            $this->error('无效邮箱');
        }
        $data = [
            'id' => $user['id'],
            'auth' => 1
        ];
        $res = $this->UserModel->isUpdate(true)->save($data);
        if (!$res) {
            $this->error('认证失败');
        } else {
            cookie('LoginUser', md5($user['id'] . $user['salt']));
            $this->success('认证成功', url('home/user/index'));
        }
    }

    // 验证码
    public function vercode()
    {
        $config = [
            'length' => 4,
            'fontSize' => 20,
            'imageW' => 150,
            'imageH' => 40
        ];
        $captcha = new Captcha($config);
        return $captcha->entry();
    }
}
